package com.miniapp.controller;

import com.miniapp.dto.SimpleSearchDTO;
import com.miniapp.entity.MiniUserEntity;
import com.miniapp.exception.RRException;
import com.miniapp.utils.BaseUtils;
import com.miniapp.utils.QueryUtils;
import com.miniapp.utils.RequestHelper;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;

/**
 * Controller公共组件
 * 
 * @author linyuchi
 * @email xunli-03@163.com
 * @date 2018/03/18
 */
public abstract class AbstractController {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	protected MiniUserEntity getUser() {
		return (MiniUserEntity) SecurityUtils.getSubject().getPrincipal();
	}

	protected Long getUserId() {
		return getUser().getId();
	}
	/**
	 * 将request组装为SimpleSearchDTO并返回
	 * @return
	 */
	public SimpleSearchDTO getSearchDtoFromJqGrid(){
		return QueryUtils.buildSearchDtoFromJqGrid(RequestHelper.getCurrentRequest());
	}
	protected String getAppid() {
		//从header中获取appid
		String appid = RequestHelper.getCurrentRequest().getHeader("appid");

		//如果header中不存在appid，则从参数中获取token
		if (org.apache.commons.lang.StringUtils.isBlank(appid)) {
			appid = RequestHelper.getCurrentRequest().getParameter("appid");
		}
		//如果参数中没有就从appid中取
		if (org.apache.commons.lang.StringUtils.isBlank(appid)) {
			Cookie[] cookies = RequestHelper.getCurrentRequest().getCookies();
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("appid")) {
					appid = cookie.getValue();
					break;
				}
			}
		}
		if (BaseUtils.isEmpty(appid)){
			throw new RRException("不存在APPID");
		}
		return appid;
	}
}
